<template>
    <div>
        <!-- 面包屑 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addRoleDialogVisible=true">添加角色</el-button>
                </el-col>
            </el-row>
            <el-table :data="rolesList" border stripe>
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- 一级权限 -->
                        <el-row :class="['bdbottom',i1===0?'bdtop':'','vcenter','margin']" :key="item1.id" v-for="(item1,i1) in scope.row.children">
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级权限 -->
                            <el-col :span="19">
                                <el-row :class="[i2===0?'':'bdtop','vcenter']" :key="item2.id" v-for="(item2,i2) in item1.children">
                                    <el-col :span="6">
                                        <el-tag type="success" closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <!-- 三级权限 -->
                                    <el-col :span="18">
                                        <el-tag type="warning" :key="item3.id" v-for="item3 in item2.children" closable @close="removeRightById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                    </template>
                </el-table-column>
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column label="角色名称" prop="roleName"></el-table-column>
                <el-table-column label="角色名称" prop="roleDesc"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showRoles(scope.row.id)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoles(scope.row.id)">删除</el-button>
                        <el-button type="warning" icon="el-icon-share" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!-- 添加角色对话框 -->
        <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" @close="resetRolesForm">
            <el-form :model="rolesForm" :rules="rolesFormRule" ref="rolesFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="rolesForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="rolesForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="addRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addRoles">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 编辑角色对话框 -->
        <el-dialog title="编辑角色" :visible.sync="editRoleDialogVisible">
            <el-form :model="editRoleForm" :rules="rolesFormRule" ref="editRoleFormRef" label-width="100px">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="editRoleForm.roleName"></el-input>
                </el-form-item>
                <el-form-item label="角色描述">
                    <el-input v-model="editRoleForm.roleDesc"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="editRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editRoles">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 权限分配对话框 -->
        <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="setRightDialogClosed">
            <!-- 树形控件 -->
            <!-- show-checkbox:添加复选框  node-key：唯一标识节点的属性  default-expand-keys：是否展开所有节点  default-expanded-keys:需要展开的数组 -->
            <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="allotRights">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      addRoleDialogVisible: false,
      editRoleDialogVisible: false,
      setRightDialogVisible: false,
      rolesForm: {
        roleName: '',
        roleDesc: ''
      },
      rolesFormRule: {
        roleName: { required: true, message: '不为空！', trigger: 'blur' }
      },
      editRoleForm: {},
      rightslist: [],
      treeProps: {
        // 树形控件的绑定对象,label为要展示的名称，children为子节点的属性名
        label: 'authName',
        children: 'children'
      },
      defKeys: [],
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //  初始化数据
    async getRolesList() {
      const res = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
    },
    // 删除权限
    async removeRightById(role, id) {
      const confirmResult = await this.$confirm('此操作将删除用户权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return
      const res = await this.$http.delete('roles/' + role.id + '/rights/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败！')
      role.children = res.data
    },
    resetRolesForm() {
      this.$refs.rolesFormRef.resetFields()
    },
    // 添加角色
    async addRoles() {
      this.$refs.rolesFormRef.validate(async valid => {
        if (!valid) return
        const res = await this.$http.post('roles', this.rolesForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success('创建角色成功！')
        this.addRoleDialogVisible = false
        this.getRolesList()
      })
    },
    // 获取角色信息
    async showRoles(id) {
      const res = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('获取角色失败')
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    // 提交修改角色
    editRoles() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if (!valid) return
        const res = await this.$http.put(`roles/${this.editRoleForm.roleId}`, { roleName: this.editRoleForm.roleName, roleDesc: this.editRoleForm.roleDesc })
        if (res.meta.status !== 200) return this.$message.error('修改失败')
        this.editRoleDialogVisible = false
        this.getRolesList()
        this.$message.success('修改成功')
      })
    },
    // 删除角色
    async removeRoles(id) {
      const confirmResult = await this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return
      const res = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功!')
      this.getRolesList()
    },
    // 获取权限列表并将行内数据渲染到结构
    async showSetRightDialog(role) {
      this.roleId = role.id
      const res = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取权限失败')
      this.rightslist = res.data
      this.getRightsId(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    getRightsId(data, arr) {
      if (!data.children) return arr.push(data.id)
      data.children.forEach(item => this.getRightsId(item, arr))
    },
    setRightDialogClosed() {
      this.defKeys = []
    },
    async allotRights() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const res = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('授权失败')
      this.$message.success('授权成功！')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
    margin: 7px;
}
.bdtop {
    border-top: 1px solid #eee;
}
.bdbottom {
    border-bottom: 1px solid #eee;
}
.vcenter {
    display: flex;
    align-items: center;
}
.margin {
    margin: 0 50px;
}
</style>
